{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 静态方法和类方法\n",
    "\n",
    "静态方法和类方法是这样创建的：将它们分别包装在`staticmethod`和`classmethod`类的对象中。\n",
    "\n",
    "1. **静态方法**的定义中没有参数`self`，可直接通过类来调用。\n",
    "2. **类方法**的定义中包含类似于`self`的参数，通常被命名为`cls`。对于类方法，也可通过对象直接调用，但参数`cls`将自动关联到类\n",
    "\n",
    "以下两种方式都是等效的:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "class MyClass:\n",
    "    def smeth():\n",
    "        print(\"This is a static method\")\n",
    "    smeth = staticmethod(smeth)  # 定义静态方法\n",
    "    \n",
    "    def cmeth(cls):\n",
    "        print('This is a class method of', cls)\n",
    "    cmeth = classmethod(cmeth) # 定义类方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "class MyClass1:\n",
    "    @staticmethod # 定义静态方法\n",
    "    def smeth():\n",
    "        print(\"This is a static method\")\n",
    "        \n",
    "    @classmethod  # 定义类方法\n",
    "    def cmeth(cls):\n",
    "        print('This is a class method of', cls)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "定义这些方法后，就可像下面这样使用它们（无需实例化类）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "This is a static method\n",
      "None\n",
      "This is a class method of <class '__main__.MyClass'>\n",
      "None\n",
      "This is a static method\n",
      "None\n",
      "This is a class method of <class '__main__.MyClass1'>\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "print(MyClass.smeth())\n",
    "print(MyClass.cmeth())\n",
    "print(MyClass1.smeth())\n",
    "print(MyClass1.cmeth())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
